<template>
  <div class="earthquakeServer-trigger">
    <ContentWrap>
      <div>
        <h2>地震触发</h2>
        <p>主要用于日常测试、演练地震。</p>
      </div>
      <el-divider />
      <div style="display: flex; justify-content: space-between">
        <div style="width: 34%">
          <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-form-item label="发震时刻：" prop="earthquakeTime">
              <el-date-picker
                v-model="ruleForm.earthquakeTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择"
                :disabled-date="disabledDate"
              />
            </el-form-item>
            <el-form-item label="纬度：" prop="latitude">
              <el-input
                v-model="ruleForm.latitude"
                @input="
                  (value) =>
                    (ruleForm.latitude = value
                      .replace(/[^0-9.]/g, '')
                      .replace(/^(\d+\.\d{0,2}).*$/, '$1'))
                "
                placeholder="点击地图可获得经纬度及参考位置"
              />
            </el-form-item>
            <el-form-item label="经度：" prop="longitude">
              <el-input
                v-model="ruleForm.longitude"
                @input="
                  (value) =>
                    (ruleForm.longitude = value
                      .replace(/[^0-9.]/g, '')
                      .replace(/^(\d+\.\d{0,2}).*$/, '$1'))
                "
                placeholder="点击地图可获得经纬度及参考位置"
              />
            </el-form-item>
            <el-form-item label="参考位置：" prop="referenceLocation">
              <el-input
                v-model="ruleForm.referenceLocation"
                placeholder="点击地图可获得经纬度及参考位置"
              />
            </el-form-item>
            <el-form-item label="震级：" prop="earthquakeMagnitude">
              <el-input
                v-model="ruleForm.earthquakeMagnitude"
                @input="
                  (value) =>
                    (ruleForm.earthquakeMagnitude = value
                      .replace(/[^0-9.]/g, '')
                      .replace(/^(\d+\.\d{0,1}).*$/, '$1'))
                "
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="震源深度：" prop="depth">
              <el-input
                v-model="ruleForm.depth"
                @input="(value) => (ruleForm.depth = value.replace(/[^\d]/g, ''))"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="地震类型：" prop="earthquakeType">
              <el-select
                placeholder="请选择"
                v-model="ruleForm.earthquakeType"
                style="width: 300px"
              >
                <el-option
                  v-for="option in earthquakeTypes"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <div style="width: 100px;height:40px;line-height: 40px;">
                <el-checkbox style="width: 0px" v-model="ruleForm.isPublish" size="large" />
                <span style="font-size: 16px">是否推送</span>
              </div>
              <div style="margin: 0; padding: 0">
                选择推送则会对外推送地震消息，如：通过微信群、钉钉以及接入的第三方系统推送地震消息、地震文件
              </div>
            </el-form-item>
            <el-form-item>
              <div style="width: 100px;height:40px;line-height: 40px;">
                <el-checkbox style="margin-right: 18px;" v-model="ruleForm.bida" size="large" />
                <span style="font-size: 16px">必达通</span>
              </div>
              <span style="margin-left: 80px; margin-right: 80px; font-size: 16px"></span>
              <div style="width: 100px;height:40px;line-height: 40px;">
                <el-checkbox style="margin-right: 18px;" v-model="ruleForm.phoneConference" size="large" />
                <span style="font-size: 16px">电话会议</span>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="storage">保存</el-button>
              <el-button @click="setClose()">关闭</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div style="width: 64%">
          <div id="mapDiv" style="width: 700px; height: 600px"></div>
        </div>
      </div>
    </ContentWrap>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus'
import * as earthquakeServerApi from '@/api/earthquake/earthquakeServer'
import {getDefaultCoordinates} from "@/api/earthquake/earthquakeServer";

const emit = defineEmits(['setClose'])
const message = useMessage() // 消息弹窗
// 响应式数据
const ruleForm = ref({
  earthquakeTime: '',
  // 纬度
  latitude: '39.91',
  // 经度
  longitude: '116.39',
  referenceLocation: '北京市天安门',
  earthquakeMagnitude: null,
  depth: null,
  earthquakeType: 2,
  isPublish: false,
  bida: false,
  phoneConference: false
})
const earthquakeTypes = [
  { label: '正式地震', value: 1 },
  { label: '测试地震', value: 2 },
  { label: '演练地震', value: 3 },
  { label: '自动地震', value: 4 }
]
// 校验
const rules = reactive({
  earthquakeTime: [{ required: true, message: '不可为空', trigger: 'blur' }],
  latitude: [{ required: true, message: '不可为空', trigger: 'blur' }],
  longitude: [{ required: true, message: '不可为空', trigger: 'blur' }],
  referenceLocation: [{ required: true, message: '不可为空', trigger: 'blur' }],
  earthquakeMagnitude: [{ required: true, message: '不可为空', trigger: 'blur' }],
  depth: [{ required: true, message: '不可为空', trigger: 'blur' }],
  earthquakeType: [{ required: true, message: '不可为空', trigger: 'blur' }]
})

const disabledDate = (time) => {
  return time.getTime() > Date.now() // 禁用当前时间之后的日期
}

//重置表单
const resetForm = () => {
  try{
    const defCoordinates = earthquakeServerApi.getDefaultCoordinates().then((res) => {
      console.log('res.longitude:'+res.longitude)
      if(res == null || res.latitude == undefined || res.longitude == undefined){
        // 在这里处理异常
        ruleForm.value.latitude = '39.90'
        ruleForm.value.longitude = '116.39'
        ruleForm.value.referenceLocation = '北京市天安门'
      }else{
        ruleForm.value.latitude = res.latitude
        ruleForm.value.longitude = res.longitude
        ruleForm.value.referenceLocation = res.province
      }
    })
  } catch (error) {
    // 在这里处理异常
    ruleForm.value.latitude = '39.90'
    ruleForm.value.longitude = '116.39'
    ruleForm.value.referenceLocation = '北京市天安门'
  }
  ruleForm.value.earthquakeTime = ''
  ruleForm.value.earthquakeMagnitude = null
  ruleForm.value.depth = null
  ruleForm.value.earthquakeType = 2
  ruleForm.value.isPublish = false
  ruleForm.value.bida = false
  ruleForm.value.phoneConference = false
}

//手动触发地震
const storage = async () => {
  await earthquakeServerApi.saveEarthquake(ruleForm.value).then((res) => {
    console.log('结果是' + res)
    if (res === 1) {
      resetForm()
    } else if (res === -1) {
      message.error('地震信息已存在')
    }
  })
}
const setClose = () => {
  emit('setClose', true)
}
// 初始化天地图
const provinceName = ref('')
const cityName = ref('')
let map
let zoom = 12
let geocode

const searchResult = (result) => {
  console.log(result, '111')
  if (result.getStatus() == 0) {
    let addressComponent = result.getAddressComponent()
    console.log(addressComponent.address, '5555')
    if (provinceName.value == undefined || cityName.value == undefined) {
      ruleForm.value.referenceLocation = addressComponent.address
    } else {
      if (provinceName.value == cityName.value) {
        ruleForm.value.referenceLocation = provinceName.value + result.addressComponent.county
      } else {
        ruleForm.value.referenceLocation =
          provinceName.value + cityName.value + result.addressComponent.county
      }
    }
  } else {
    ElMessage({
      message: '未能解析到当前位置',
      type: 'warning'
    })
  }
}

const initwxMap = () => {
  map = new T.Map('mapDiv')
  // 坐标
  map.centerAndZoom(new T.LngLat(ruleForm.value.longitude, ruleForm.value.latitude), zoom)
  //创建对象
  geocode = new T.Geocoder()
  // 地图类型
  map.setMapType(TMAP_HYBRID_MAP)
  //创建图片对象位置标识
  var icon = new T.Icon({
    iconUrl: '/static/assets/poi/zh.png',
    iconSize: new T.Point(25, 25),
    iconAnchor: new T.Point(10, 25)
  })
  //向地图上添加自定义标注
  var marker = new T.Marker(
    new T.LngLat(Number(ruleForm.value.longitude), Number(ruleForm.value.latitude)),
    { icon: icon }
  )
  map.addOverLay(marker)
  // 注册点击事件
  map.addEventListener('click', async (e) => {
    // 这里假设e.lnglat是包含经纬度的对象
    if (e.lnglat) {
      // 纬度
      ruleForm.value.latitude = e.lnglat.lat.toFixed(2)
      // 经度
      ruleForm.value.longitude = e.lnglat.lng.toFixed(2)
      // 清除在此之前的遮盖物
      map.clearOverLays()
      //创建图片对象位置标识
      var icon = new T.Icon({
        iconUrl: '/static/assets/poi/zh.png',
        iconSize: new T.Point(25, 25),
        iconAnchor: new T.Point(10, 25)
      })
      //向地图上添加自定义标注
      var marker = new T.Marker(
        new T.LngLat(Number(ruleForm.value.longitude), Number(ruleForm.value.latitude)),
        { icon: icon }
      )
      map.addOverLay(marker)
      const lonAndLat = `${ruleForm.value.longitude},${ruleForm.value.latitude}`
      try {
        const response = await earthquakeServerApi.getNameList(lonAndLat)
        provinceName.value = response.provinceName
        cityName.value = response.cityName
        console.log(e.lnglat)
        geocode.getLocation(e.lnglat, searchResult)
      } catch (error) {
        console.log('失败123')
        // 在这里处理异常
      }
    } else {
      ElMessage({
        message: '无法选中',
        type: 'warning'
      })
    }
  })
}

watch(
  () => ruleForm.value.latitude,
  async () => {
    if (map) {
      // 清除在此之前的遮盖物
      map.clearOverLays()
      //创建图片对象位置标识
      var icon = new T.Icon({
        iconUrl: '/static/assets/poi/zh.png',
        iconSize: new T.Point(25, 25),
        iconAnchor: new T.Point(10, 25)
      })
      //向地图上添加自定义标注
      var marker = new T.Marker(
        new T.LngLat(Number(ruleForm.value.longitude), Number(ruleForm.value.latitude)),
        { icon: icon }
      )
      map.addOverLay(marker)
      map.centerAndZoom(new T.LngLat(ruleForm.value.longitude, ruleForm.value.latitude), zoom)
      const lonAndLat = `${ruleForm.value.longitude},${ruleForm.value.latitude}`
      try {
        const response = await earthquakeServerApi.getNameList(lonAndLat)
        provinceName.value = response.provinceName
        cityName.value = response.cityName
        geocode.getLocation(
          new T.LngLat(ruleForm.value.longitude, ruleForm.value.latitude),
          searchResult
        )
      } catch (error) {
        console.log('失败123')
        // 在这里处理异常
      }
    }
  }
)

watch(
  () => ruleForm.value.longitude,
  async () => {
    if (map) {
      // 清除在此之前的遮盖物
      map.clearOverLays()
      //创建图片对象位置标识
      var icon = new T.Icon({
        iconUrl: '/static/assets/poi/zh.png',
        iconSize: new T.Point(25, 25),
        iconAnchor: new T.Point(10, 25)
      })
      //向地图上添加自定义标注
      var marker = new T.Marker(
        new T.LngLat(Number(ruleForm.value.longitude), Number(ruleForm.value.latitude)),
        { icon: icon }
      )
      map.addOverLay(marker)
      map.centerAndZoom(new T.LngLat(ruleForm.value.longitude, ruleForm.value.latitude), zoom)
      const lonAndLat = `${ruleForm.value.longitude},${ruleForm.value.latitude}`
      try {
        const response = await earthquakeServerApi.getNameList(lonAndLat)
        provinceName.value = response.provinceName
        cityName.value = response.cityName
        geocode.getLocation(
          new T.LngLat(ruleForm.value.longitude, ruleForm.value.latitude),
          searchResult
        )
      } catch (error) {
        console.log('失败123')
        // 在这里处理异常
      }
    }
  }
)

// 获取当前时间
const gettime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  ruleForm.value.earthquakeTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

onMounted(() => {
  resetForm()
  initwxMap()
  gettime()
})
</script>

<style scoped>
</style>
